const _ = require("lodash");
const util = require("./util");

const getViewForSwagger = swaggerData => {
  const { definitions, paths, info, host, basePath } = swaggerData;

  const data = {
    info, // 文档相关信息
    host, // 主机名
    basePath, // 上下文
    definitions: [], // 定义
    methods: [] // 接口方法
  };

  // 解析接口
  _.forEach(paths, (api, path) => {
    let request = {
      path,
      deprecated: false,
      method: "",
      methodName: "",
      summary: "",
      tags: [],
      parameters: {},
      response: {}
    };
    _.forEach(api, (value, method) => {
      const schema = value.responses[200].schema;
      let response = "any";
      if (schema && _.isString(schema.$ref)) {
        const segments = schema.$ref.split("/");
        if (segments.length > 0) {
          const resType = segments[segments.length - 1];
          if (isConstantType(resType)) {
            response = resType.replace(/«/g, "<").replace(/»/g, ">");
          } else {
            response = resType.replace(/«/g, "").replace(/»/g, "");
          }
        }
      } else if (schema) {
        response = schema.type;
      }

      const parameters = value.parameters;
      if (parameters) {
        parameters.forEach(item => {
          if (item) {
            if (item.schema && _.isString(schema.$ref) && item.schema.$ref) {
              const segments = item.schema.$ref.split("/");
              if (segments.length > 0) {
                const resType = segments[segments.length - 1];
                if (isConstantType(resType)) {
                  item.schema.value = resType
                    .replace(/«/g, "<")
                    .replace(/»/g, ">");
                } else {
                  item.schema.value = resType
                    .replace(/«/g, "")
                    .replace(/»/g, "");
                }
              }
            }
          }
        });
      }

      request.parameters = parameters;
      request.method = method;
      request.methodName = value.operationId;
      request.summary = value.summary;
      request.tags = value.tags;
      request.deprecated = value.deprecated;
      request.response = response;
    });
    data.methods.push(request);
  });

  // 解析定义
  _.forEach(definitions, (definition, name) => {
    data.definitions.push({
      name: name,
      description: definition.description,
      tsType: util.convertType(definition, swaggerData)
    });
  });
  return data;
};

const isConstantType = type => {
  const reg = /«([a-zA-Z]+)»/;
  const result = reg.exec(type);
  if (result) {
    const tp = result[1].toLocaleLowerCase();
    if (["string", "number", "integer", "boolean", "array"].includes(tp)) {
      return true;
    }

    return false;
  }

  return false;
};

module.exports.getViewForSwagger = getViewForSwagger;
